<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] &raquo; ".__("Product List");
$page_title=__("Product List");

if(!$pv["task"]["Products"]){
	$errmsg="<h2>$page_title</h2>".format_err(__("You do not have the privilege to manage products."));

	print format_admin_page($errmsg, $this_title);
	exit();
}

$add_edit_file=$vars["file"]["admin"]["add_edit_product"];

$item_per_page=$vars['admin_item_per_page'];

$cats=get_all_subcat_by_maincat();
for($i=0,$t=count($cats);$i<$t;$i++){
	$r_cat[$i]=$cats[$i]["id"];
	$r_cat_d[$cats[$i]["id"]]=cat_full_display($cats[$i]["id"]);
}
$search_options["prod_type"]["option"] = $r_prodtype=array("n","p");
$search_options["prod_type"]["option_display"] = $r_prodtype_d=array("n"=>__("Normal"),"p"=>__("Package"));
$search_options["prod_type"]["display"] = __("Product Type");
$search_options["catid"]["option"] = $r_cat;
$search_options["catid"]["option_display"] = $r_cat_d;
$search_options["catid"]["display"] = __("Category");
$search_options["status"]["option"] = $r_status=array("active","inactive","deleted");
$search_options["status"]["option_display"] = $r_status_d=array("active"=>__("Active"),"inactive"=>__("Inactive"),"deleted"=>__("Deleted"));
$search_options["status"]["display"] = __("Status");

//#####PRODUCT POST#####
if($_POST["__req"]){
	if(!$post_s["id"] || !is_numeric($post_s["id"]) || $post_s["id"]<=0){
		$errmsg.=__("Invalid product ID provided.")."<br />\n";
	}elseif(!@mysql_num_rows(mysql_query("select * from $db->products where id='$post_d[id]'"))){
		$errmsg.=replace_tag(__("Product ID: '<%id%>' does not exist in the system."), array("<%id%>"=>$post_h["id"]))."<br />\n";
	}

	if(!$errmsg){
		if(!mysql_query($sql="update $db->products set status='deleted' where id='$post_d[id]'")){
			$errmsg.=__("Error deleting the product.")."<br />\n<br />\n".__("SQL:")." $sql<br />\n<br />\n".__("Error:")." ".mysql_error()."<br />\n";
			$critical_error=$errmsg;
		}else{
			$msg=replace_tag(__("The product ID: '<%id%>' has been successfully deleted."), array("<%id%>"=>$post_h["id"]))."<br />\n";
		}
	}

	//log critical error
	if($critical_error){
		$error_type_code="a-pd";
		$affected_uid=0;
		log_activity('e', 'a', $aid, 'n', $affected_uid, $error_type_code, $critical_error);
	}

	$msg=$msg? format_msg($msg) : "";
	$errmsg=$errmsg? format_err(__("There is some error(s):")."<br />\n<br />\n$errmsg") : "";
}

//#####SEARCH#####
if($_GET["s"]){
	$searching=1;
	$search_query=prod_search($_GET);
}

//textbox search, prefix "_sp_"
$r_textsearch=array("id"=>__("Product ID"),"refno"=>__("Reference No."),"title"=>__("Title"));

$searchfields_ordering=array("id","refno","title","prod_type","catid","status");
$search_ui=build_admin_search_ui($searching, $this_file, $search_options, $r_textsearch, $searchfields_ordering, $inputbox_style);
//#####END SEARCH#####

//javascript
ob_start();
?>
<script type="text/javascript" src="<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js"); ?>"></script>
<script type="text/javascript">
jQuery(document).ready(function(j){
	j('a[@name=delete_prod]').click(function(){
		id = j(this).attr('rel');
		confirm_text='<?php echo AddSlashes(__("Delete this product with ID: <#id#>, are you sure?")); ?>';
		confirm_text=confirm_text.replace(/\<#id#\>/g, id);
		if(confirm(confirm_text)){
			j('input[@name=id]').val(id);
			j('form[@name=prod_form]').submit();
		}
		return false;
	});
});
</script>
<?php
$jvscript = ob_get_clean();

//#####LIST PRODUCT#####
if($searching){
	$count_sql=$search_query["count_sql"];
	$record_sql=$search_query["record_sql"];
}else{
	$count_sql="select count(*) from $db->products where status!='deleted'";
	$record_sql="select * from $db->products where status!='deleted' order by id limit <%limit_start%>, <%limit%>";
}

//#####EXPORT
if($_GET['export_excel']){
	$record_sql = substr($record_sql, 0, strlen($record_sql) - strlen(" limit <%limit_start%>, <%limit%>"));
	$t=@mysql_num_rows($r=mysql_query($record_sql));
	for($i=0;$i<$t;$i++){
		$record = mysql_fetch_assoc($r);
		//get products for a package
		if($record["prod_type"]=="p"){
			$prod_list=$this_pck_prods="";
			$t2=@mysql_num_rows($r2=mysql_query("select * from $db->package_detail where pkid='$record[id]'"));
			for($j=0;$j<$t2;$j++){
				$pck_prod=mysql_fetch_assoc($r2);
				if(!isset($prods[$pck_prod["pid"]])) {
					$prods[$pck_prod["pid"]]=@mysql_fetch_assoc(mysql_query("select title, refno from $db->products where id='$pck_prod[pid]' limit 1")) or false;
				}
				$prod_list.=($prods[$pck_prod["pid"]]? __("ID").__(":")." $pck_prod[pid] ".__(",")." ".__("Ref #").__(":")." ".$prods[$pck_prod["pid"]]["refno"].__(",")." ".$prods[$pck_prod["pid"]]["title"]." ".__("Quantity").__(":")." ".$pck_prod["qty"] : "<span class='red'>".replace_tag(__("Product ID '<%id%>' does not exist!"), array("<%id%>"=>$pck_prod["pid"]))."</span>")."<br />\n";
			}
			$prod_title = $prod_list;
		}else{
			$prod_title = $record["title"];
		}
		//quantity
		$qty = $record["prod_type"]=="n"? $record["qty_type"]=='u'? "Unlimited" : $record["qty"] : "N/A";
		//category
		$cat = $r_cat_d[$record["catid"]];
		$status = $r_status_d[$record["status"]];
		
		$run_no = $i + 1;
		$report_excel.="
		<tr>".
			"<td>$run_no</td>".
			"<td>$record[refno]</td>".
			"<td>$prod_title</td>".
			"<td>$record[bv]</td>".
			"<td>$record[dp]</td>".
			"<td>$record[rp]</td>".
			"<td>$qty</td>".
			"<td>$status</td>".
			"<td>$cat</td>".
		"</tr>";
	}
	ob_start();
	?>
<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<meta http-equiv="Content-type" content="text/html;charset=utf-8" />
<style id="Classeur1_16681_Styles">
</style>
<style type='text/css'>
td{
	border:1px solid #000;
}
tr.e_header td{
	font-weight:bold;
	background:#aaa;
}
</style>
</head>
<body>

<div id="Classeur1_16681" align=center x:publishsource="Excel">

<table x:str border=0 cellpadding=0 cellspacing=0 style="border-collapse: collapse">
<tr class=e_header><td nowrap colspan=23>Exported at <?php echo ndate($vars['date_format']); ?></td></tr>
<tr class=e_header><td nowrap>No</td><td nowrap>Product Code</td><td nowrap>Title</td><td nowrap>BV</td><td nowrap>DP</td><td nowrap>RP</td><td nowrap>Quantity</td><td nowrap>Status</td><td nowrap>Category</td></tr>
<?php echo $report_excel; ?>
</table>
</div>
</body>
</html>
	<?php 

	$xls = ob_get_clean();
	$filename = "product_".date('Ymd').".xls";
	header ( "Content-Type: application/force-download" );
	header ( "Content-Type: application/octet-stream" );
	header ( "Content-Type: application/download" );
	header ( "Content-Type: application/ms-excel" );
	header ( "Content-Disposition: attachment; filename=".$filename );
	header ( "Content-Transfer-Encoding: binary" );
	header ( "Accept-Ranges: bytes" );
	header ( "Content-Length: ".strlen ( $xls ) );
	echo $xls;
	exit;
}
//#####END EXPORT

$cur_page=$_GET["nav"];
$total_record=@mysql_result(mysql_query($count_sql), 0);
$total_page=ceil($total_record/$item_per_page);
$page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);
$limit_start=($page-1)*$item_per_page;
$nav_link=format_page_admin($page, $total_page, $this_file);
$this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));
$k=0;
for($i=0;$i<$this_page_total;$i++){
	$prod=mysql_fetch_assoc($r);
	//get products for a package
	if($prod["prod_type"]=="p"){
		$prod_list=$this_pck_prods="";
		$t=@mysql_num_rows($r2=mysql_query("select * from $db->package_detail where pkid='$prod[id]'"));
		for($j=0;$j<$t;$j++){
			$pck_prod=mysql_fetch_assoc($r2);
			if(!isset($prods[$pck_prod["pid"]])) {
				$prods[$pck_prod["pid"]]=@mysql_fetch_assoc(mysql_query("select title, refno from $db->products where id='$pck_prod[pid]' limit 1")) or false;
			}
			$prod_list.=($prods[$pck_prod["pid"]]? __("ID").__(":")." $pck_prod[pid] ".__(",")." ".__("Ref #").__(":")." ".$prods[$pck_prod["pid"]]["refno"].__(",")." ".$prods[$pck_prod["pid"]]["title"]." ".__("Quantity").__(":")." ".$pck_prod["qty"] : "<span class='red'>".replace_tag(__("Product ID '<%id%>' does not exist!"), array("<%id%>"=>$pck_prod["pid"]))."</span>")."<br />\n";
		}
	}
	$edit_link="<a href=\"$add_edit_file?type=edit&id=".$prod["id"]."\"><img src='".M_URL."/images/icons/edit.png'></a>";
	$del_link="<a href='#' name='delete_prod' rel='".$prod["id"]."'><img src='".M_URL."/images/icons/delete.png'></a>";
	$prod_row.="
	<tr class='row$k'>".($pv["task"]["Add/Update Products"]? "
		<td>$edit_link</td>
		<td>$del_link</td>" : "")."
		<td>".$prod["id"]."</td>
		<td class='center'>".($prod["image_file"] && file_exists(PROD_ROOT."/".$prod["id"]."/thumb/".$prod["image_file"])? "<img src='".PROD_URL."/".$prod["id"]."/thumb/".$prod["image_file"]."' />" : __("N/A"))."</td>
		<td>".$prod["refno"]."</td>
		<td>".$prod["title"].($prod["prod_type"]=="p"? "<br />\n<br />\n$prod_list" : "")."</td>
		<td>".($prod["prod_type"]=="p"? ($prod["bv_fix"]=="n"? number_format(calc_package_point("bv", $prod['id']), 2) : number_format($prod["bv"], 2)) : number_format($prod["bv"], 2))."</td>
		<td>".($prod["prod_type"]=="p"? ($prod["dp_fix"]=="n"? number_format(calc_package_point("dp", $prod['id']), 2) : number_format($prod["dp"], 2)) : number_format($prod["dp"], 2))."</td>
		<td>".($prod["prod_type"]=="p"? ($prod["rp_fix"]=="n"? number_format(calc_package_point("rp", $prod['id']), 2) : number_format($prod["rp"], 2)) : number_format($prod["rp"], 2))."</td>
		<td>".($prod["prod_type"]=="n"? $prod["qty_type"]=='u'? __("Unlimited") : $prod["qty"] : __("N/A"))."</td>
		<td>".$r_status_d[$prod["status"]]."</td>
		<td>".$r_cat_d[$prod["catid"]]."</td>
		<td>".date($vars["system_date_format_short"], strtotime($prod["cdate"]))."</td>
	</tr>";
	$k=1-$k;
}

//listing text
$listing_text=replace_tag(($searching? __("Search returned <%x%> <%product%>.") : __("Listing <%x%> <%product%>.")), array("<%x%>"=>strval($total_record), "<%product%>"=>$total_record>1? __("products") : __("product"))).($searching? " <a href='$this_file'>".__("Clear Search and Refresh")."</a>." : "");

//listing
$prod_list=($errmsg || $msg? $errmsg.$msg : "").
($pv["task"]["Add/Update Products"]? "<input type='button' value='".__("Add Product")."' onclick=\"window.location='$add_edit_file?type=add';\" />" : "")."
<form name='prod_form' method='post' action='$this_file".($_SERVER["QUERY_STRING"]? "?".$_SERVER["QUERY_STRING"] : "")."'>
<input type='hidden' name='__req' value='1' />
<input type='hidden' name='id' />
</form>
$search_ui<br />\n
$listing_text $nav_link
<table class='aml_table' style='width:1000px;'>
	<tr class='aml_header'>".($pv["task"]["Add/Update Products"]? "
		<td width='18'><img src='".M_URL."/images/icons/edit.png'></td>
		<td width='18'><img src='".M_URL."/images/icons/delete.png'></td>" : "")."
		<td>".__("No")."</td>
		<td>".__("Image")."</td>
		<td>".__("Reference No.")."</td>
		<td>".__("Title")."</td>
		<td>BV</td>
		<td>DP</td>
		<td>CP</td>
		<td>".__("Quantity")."</td>
		<td>".__("Status")."</td>
		<td>".__("Category")."</td>
		<td>".__("Created Date")."</td>
	</tr>
	$prod_row
</table>
<a href='$this_file?$_SERVER[QUERY_STRING]&export_excel=1'>".__("Export Excel")."</a><br />
</form>";
//#####END PRODUCT LIST#####

$content="<h2>$page_title</h2>$prod_list";

print format_admin_page($content, $this_title, $jvscript);

function prod_search($in_get){
	global $vars, $search_options;
	$db=$vars["db"];

	$get=$in_get;
	$search_type="and";
	$r_like_search=array("refno","title");
	//format search string
	foreach($get as $field=>$value){
		$value=trim($value);
		//search checkbox option
		if(preg_match('/^_so_/', $field)){
			preg_match('/(?<=_so_).+(?=__)/', $field, $matchf);
			$f=$matchf[0];
			preg_match('/(?<=__).+$/', $field, $matchv);
			$v=$matchv[0];
			$r_searchquery[$f].=($r_searchquery[$f]? "," : "")."'$v'";
		}
		//db field name search
		if(substr($field, 0, strlen("_sp_"))=="_sp_"){
			if(strlen($value)){
				$db_fieldname=substr($field, strlen("_sp_"));
				$db_fieldname_q.=($db_fieldname_q? " and " : "")."(".(in_array($db_fieldname, $r_like_search)? format_search_field_like($db_fieldname, $value) : format_search_field($db_fieldname, $value)).")";
			}
		}
	}
	if(isset($r_searchquery)){
		foreach($r_searchquery as $field => $query){
			$option_q.=($option_q? " and " : "")."$field in ($query)";
		}
	}else{
		$option_q="1=1";
	}
	$db_fieldname_q=$db_fieldname_q? $db_fieldname_q : "1=1";

	$count_sql="select count(*) from $db->products where $option_q and $db_fieldname_q";
	$record_sql="select * from $db->products where $option_q and $db_fieldname_q order by id limit <%limit_start%>, <%limit%>";

	return array("count_sql"=>$count_sql, "record_sql"=>$record_sql);
}
?>